package com.wuxiaolong.tools.controller;


import com.wuxiaolong.tools.servive.impl.OssFileServiceImpl;
import com.wuxiaolong.tools.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 1.通过文章连接获取文章的内容
 * 2.下载文章中的图片到本地
 * 3.文章中图片连接替换为本地的图片链接
 */
@Controller
@RequestMapping("/html/extract")
@Slf4j
public class HtmlExtractionController {

    private static String imgFix = ".jpg";
    public  static Map<String, String> keyValueMap = new HashMap<>();

    @Autowired
    private OssFileServiceImpl fileService;

    @GetMapping("/page")
    public String index(){
        return "/pages/html_extraction";
    }



    @PostMapping("/extract")
    @ResponseBody
    public Map html2RichText(@RequestBody String jsonStr){
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        String srcUrl = jsonStr;
        if(StringUtils.hasText(srcUrl)){

            String content = HttpClientUtil.get(srcUrl);
            Document document = Jsoup.parse(content);

            //例如文章：https://mp.weixin.qq.com/s/GoIZdwt5gJje-ZWMBUoBPw

            StringBuilder stringBuilder = new StringBuilder();
            //.rich_media_content
            List<Element> elementList = document.select("#img-content");
            stringBuilder.append(elementList.toString());
            System.out.println("========================================================================");

            if(!CollectionUtils.isEmpty(elementList)){
                elementList.forEach(e-> paser(e));
            }
//
            //替换jsoup自动src改成data-src属性
            String articleContent = stringBuilder.toString();

            for(String url: keyValueMap.keySet()){
                articleContent = org.apache.commons.lang3.StringUtils.replace(articleContent,url, keyValueMap.get(url));
            }
            articleContent = articleContent.replace("data-src", "src");
//            System.out.println("articleContent:" + articleContent);
            result.put("data", articleContent);
        }
        return result;
    }

    /**
     * 判断element元素是否图片，如果是，则下载到本地
     * @param element
     */
    private void paser(Element element) {
        Tag tag = element.tag();
        String tagName = tag.getName();
        if (tagName.equals("img")) {
            //img(element, filePath, filePathStart);
            img(element,fileService);
        }
        List<Element> children = element.children();
        if(!CollectionUtils.isEmpty(children)){
            children.forEach(e->{
                //穷举到所有根节点
                downloadImg(e);
            });
        }else{
            return;
        }
    }

    /**
     * 判断element元素是否图片，如果是，则下载到本地
     * @param element
     */
    public void downloadImg(Element element){

        Tag tag = element.tag();
        String tagName = tag.getName();
        if (tagName.equals("img")) {
            //img(element, filePath, filePathStart);
            img(element,fileService);
        }
        List<Element> children = element.children();
        if(!CollectionUtils.isEmpty(children)){
            children.forEach(e->{
                //穷举到所有根节点
                downloadImg(e);
            });
        }else{
            return;
        }

    }

    private static void img(Element element,OssFileServiceImpl fileService) {

        String url = element.attr("data-src");
        System.out.println("data-src:" + url);
        String fix = getPicture(url,fileService);
        // todo 这里的相对路径可配置为常量
//		String url_new = "../images/" + fix;
        element.attr("src", fix);

    }



    private static String getPicture(String url,OssFileServiceImpl fileService) {

        String fileName = UUID.randomUUID().toString().replace("-","");

        // 本地下载路径
        String localFilePath = "./" + fileName + imgFix ;
        if (!url.equals("")) {
            URL ur;
            BufferedInputStream in;
            ByteArrayOutputStream outStream;
            try {
                ur = new URL(url);
                in = new BufferedInputStream(ur.openStream());
                outStream = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int length = 0;
                while ((length = in.read(buf, 0, buf.length)) != -1) {
                    outStream.write(buf, 0, length);
                }
                byte[] bytes = outStream.toByteArray();
                File fileOut = new File(localFilePath);
                FileOutputStream op = new FileOutputStream(fileOut);

                op.write(bytes);
                op.close();
                in.close();
                outStream.close();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("图片下载到本地失败",e);
            }

            // 写入oss
            try {
                File localFile = new File(localFilePath);
                String downUrl = fileService.upload(fileName+ imgFix, FileUtils.openInputStream(localFile), localFile.length());
                FileUtils.deleteQuietly(new File(localFilePath));
                keyValueMap.put(url, downUrl);
                System.out.println("oss路径:" + downUrl);
                // 在线访问路径
                return  downUrl;
            }catch (Exception e){
                log.error("图片上传oss失败",e);
            }
        }


        return "";
    }
}
